﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_ORDER.BizLogic;
using ERP_RORZE_ORDER.Common;
using ERP_RORZE_ORDER.Common.ValueObject;
using ERP_RORZE_ORDER.OrderObject.UserControls;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common.ValueObject;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using MakerHelper = ERP_RORZE_ORDER.BizLogic.MakerHelper;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_ORDER.OrderObject.Forms
{
    public partial class frm_OrderInputAdd : DevExpress.XtraEditors.XtraForm
    {
        private ucOrderInput parent;
        private DataTable dtProduct;
        private DataTable dtPurchase;
        private DataTable dtPGroup;
        private DataTable dataTable;
        private decimal price;
        AutoCompleteStringCollection itemProductID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemProductName = new AutoCompleteStringCollection();
        ProductHelper helper = new ProductHelper(new Product());
        private LogUtils log;

        public frm_OrderInputAdd(ucOrderInput ucP)
        {
            dtProduct = helper.GetAll();
            InitializeComponent();
            parent = ucP;
            //this.CancelButton = this.btCancel;
            this.ActiveControl = cmbOrderID;
            txtExchangeRate.LostFocus += txtExchangeRate_LostFocus;
            log = new LogUtils();
            cmbProduct.LostFocus += cmbProduct_LostFocus;
        }

        void cmbProduct_LostFocus(object sender, EventArgs e)
        {
            if (cmbProduct.Items.Count <= 0)
            {
                foreach (string s in cmbProduct.AutoCompleteCustomSource)
                {
                    if (cmbProduct.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbProduct.Text = s;
                        break;
                    }
                }

            }

            if (cmbProduct.Items.Count <= 0)
            {
                DataRow[] row =
                    dtProduct.Select(OrderConstants.Entities.Product.FieldName.ProductID + " = '" + cmbProduct.Text +
                                     "'");
                if (row.Length > 0)
                {
                    txtUnit.Text = row[0][OrderConstants.Entities.Product.FieldName.UnitID].ToString();
                    txtPrice.Text =
                        (decimal.Parse(row[0][OrderConstants.Entities.Product.FieldName.Price].ToString())
                                .ToString("n2"));
                    price = decimal.Parse(row[0][OrderConstants.Entities.Product.FieldName.Price].ToString());
                    txtCurrencyPrice.Text = row[0][OrderConstants.Entities.Product.FieldName.CurrencyID].ToString();
                    txtProductName.Text = row[0][OrderConstants.Entities.Product.FieldName.ProductName].ToString();
                    txtEnglishName.Text = row[0][OrderConstants.Entities.Product.FieldName.EnglishName].ToString();
                    txtxVietName.Text = row[0][OrderConstants.Entities.Product.FieldName.VietName].ToString();
                    txtJapanName.Text = row[0][OrderConstants.Entities.Product.FieldName.JapanName].ToString();
                    txtSize.Text = row[0][OrderConstants.Entities.Product.FieldName.Size].ToString();
                    txtMakername.Text = row[0][OrderConstants.Entities.Product.FieldName.MakerName].ToString();
                    txtProducrGroup.Text = row[0][OrderConstants.Entities.Product.FieldName.GroupName].ToString();
                    txtSupplierName.Text = row[0][OrderConstants.Entities.Product.FieldName.SupplierName].ToString();
                    txtPurpose.Text = row[0][OrderConstants.Entities.Product.FieldName.PurposeName].ToString();
                    txtKind.Text = row[0][OrderConstants.Entities.Product.FieldName.KindID].ToString();
                }
            }

        }

        private void frm_ProductAdd_Load(object sender, EventArgs e)
        {
            BindDataOrder();
            BindDataProduct();
            BindDataPurchase();
            BindDataPGroup();
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            OrderInputHelper helper = new OrderInputHelper(new OrderInput());
            if (GetData(helper.ValueObject))
            {
                if (helper.Insert() > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.F2Order.OrderInput;
                    log.Task = LogConstant.Task.Insert;
                    log.Description = "OrderID: " + helper.ValueObject.OrderID + "; ProductID: " + helper.ValueObject.ProductID;
                    log.WriteLog();

                    if (Utilities.MessageConfirmationYesNo(OrderConstants.Message.AddSuccessAndQuestion))
                    {

                        //cmbOrderID.SelectedItem = cmbOrderID.Items[0];
                        cmbProduct.Text = string.Empty;
                        //dateDeadline.EditValue = null;
                        txtQuantity.Text = string.Empty;
                       // txtExchangeRate.Text = string.Empty;
                        //cmbPurchaser.SelectedItem = cmbPurchaser.Items[0];
                        //cmbPGroup.SelectedItem = cmbPGroup.Items[0];
                        //txtNote.Text = string.Empty;
                       // txtStatus.Text = string.Empty;

                        txtUnit.Text = string.Empty;
                        txtPrice.Text = string.Empty;
                        txtCurrencyPrice.Text = string.Empty;
                        txtProductName.Text = string.Empty;
                        txtEnglishName.Text = string.Empty;
                        txtxVietName.Text = string.Empty;
                        txtJapanName.Text = string.Empty;
                        txtSize.Text = string.Empty;
                        txtMakername.Text = string.Empty;
                        txtProducrGroup.Text = string.Empty;
                        txtSupplierName.Text = string.Empty;
                        txtPurpose.Text = string.Empty;
                        txtKind.Text = string.Empty;

                        lbAmount.Visible = false;
                        txtAmount.Visible = false;
                        txtCurrencyAmount.Visible = false;

                        cmbProduct.Focus();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {

                    Utilities.MessageErrorOk(OrderConstants.Message.AddFailed);
                }
                parent._action = 0;
                parent.BindDatatoGrid();
            }
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        #region Private Method
        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private bool GetData(OrderInput o)
        {
            #region Check valid
            DataTable dtCheck;
            if (Utilities.IsNullOrEmpty(cmbOrderID.SelectedValue) || cmbOrderID.SelectedItem == cmbOrderID.Items[0])
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.OrderIDCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbProduct.Text))
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.ProductCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [243_Product] where [ProductID]=N'" + cmbProduct.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.ProductInvalid, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbProduct.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(dateDeadline.EditValue))
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.DeadlineCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtQuantity.Text))
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.QuantityCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (int.Parse(txtQuantity.Text) <= 0)
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.QuantityMustGreaterZero, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtExchangeRate.Text))
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.ExchangeRateCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (decimal.Parse(txtExchangeRate.Text) <= 0)
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.ExchangeRateMustGreaterZero, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbPurchaser.SelectedValue) || cmbPurchaser.SelectedItem == cmbPurchaser.Items[0])
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.PurchaseCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbPGroup.SelectedValue) || cmbPGroup.SelectedItem == cmbPGroup.Items[0])
            {
                MessageBox.Show(OrderConstants.Message.OrderInput.PGroupCantEmpty, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            #endregion

            o.OrderID = cmbOrderID.SelectedValue.ToString();
            o.ProductID = cmbProduct.Text;
            o.Deadline = dateDeadline.DateTime.Date;
            o.Quantity = int.Parse(txtQuantity.Text);
            o.ExchangeRate = decimal.Parse(txtExchangeRate.Text);
            o.PurchaseID = cmbPurchaser.SelectedValue.ToString();
            o.PGroupID = cmbPGroup.SelectedValue.ToString();
            o.Note = txtNote.Text;
            o.Status = txtStatus.Text;
            //o.Price = decimal.Parse(price.ToString());
            o.Price = decimal.Parse(txtPrice.Text);

            return true;
        }

        private void BindDataOrder()
        {
            //OrderHelper helper = new OrderHelper(new Order());
            //DataTable dt = helper.GetAll();
            DataTable dt = BaseDAO.ExecuteQuery("Select OrderID from [243_Order] order by OrderID desc");
            DataRow row = dt.NewRow();

            //row[OrderConstants.Entities.Order.FieldName.OrderID] = string.Empty;
            row[OrderConstants.Entities.Order.FieldName.OrderID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbOrderID.DataSource = dt;
            cmbOrderID.DisplayMember = OrderConstants.Entities.Order.FieldName.OrderID;
            cmbOrderID.ValueMember = OrderConstants.Entities.Order.FieldName.OrderID;
            //cmbOrderID.Sorted = true;
            //cmbOrderID.SelectedItem = cmbOrderID.Items[0];

        }

        private void BindDataProduct()
        {
            //ProductHelper helper = new ProductHelper(new Product());
            //dtProduct = helper.GetAll();
            //DataRow row = dtProduct.NewRow();

            ////row[OrderConstants.Entities.Product.FieldName.ProductID] = string.Empty;
            //row[OrderConstants.Entities.Product.FieldName.ProductID] = null;
            //dtProduct.Rows.InsertAt(row, 0);

            //cmbProduct.DataSource = dtProduct;
            //cmbProduct.DisplayMember = OrderConstants.Entities.Product.FieldName.ProductID;
            //cmbProduct.ValueMember = OrderConstants.Entities.Product.FieldName.ProductID;
            //cmbProduct.SelectedItem = cmbProduct.Items[0];

            foreach (DataRow row in dtProduct.Rows)
            {
                itemProductID.Add(row[OrderConstants.Entities.Product.FieldName.ProductID].ToString());
            }
            cmbProduct.AutoCompleteCustomSource = itemProductID;
            
            //comboBox1.DataSource = dtProduct;
            //comboBox1.ValueMember = "ProductID";
            //comboBox1.DisplayMember = "ProductID";

            //comboBox1.Items
        }

        private void BindDataPurchase()
        {
            PurchaserHelper helper = new PurchaserHelper(new Purchaser());
            dtPurchase = helper.GetAll();
            DataRow row = dtPurchase.NewRow();

            //row[OrderConstants.Entities.Purchaser.FieldName.PurchaseName] = string.Empty;
            row[OrderConstants.Entities.Purchaser.FieldName.PurchaseID] = null;
            dtPurchase.Rows.InsertAt(row, 0);

            cmbPurchaser.DataSource = dtPurchase;
            cmbPurchaser.DisplayMember = OrderConstants.Entities.Purchaser.FieldName.PurchaseID;
            cmbPurchaser.ValueMember = OrderConstants.Entities.Purchaser.FieldName.PurchaseID;
            cmbPurchaser.SelectedItem = cmbPurchaser.Items[0];

        }

        private void BindDataPGroup()
        {
            PGroupHelper helper = new PGroupHelper(new PGroup());
            dtPGroup = helper.GetAll();
            DataRow row = dtPGroup.NewRow();

            //row[OrderConstants.Entities.PGroup.FieldName.PGroupID] = string.Empty;
            row[OrderConstants.Entities.PGroup.FieldName.PGroupID] = null;
            dtPGroup.Rows.InsertAt(row, 0);

            cmbPGroup.DataSource = dtPGroup;
            cmbPGroup.DisplayMember = OrderConstants.Entities.PGroup.FieldName.PGroupID;
            cmbPGroup.ValueMember = OrderConstants.Entities.PGroup.FieldName.PGroupID;
            cmbPGroup.SelectedItem = cmbPGroup.Items[0];

        }
        #endregion

        private void cmbProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!Utilities.IsNullOrEmpty(cmbProduct.SelectedValue) || cmbProduct.SelectedItem != cmbProduct.Items[0])
            {
                DataRow[] row = dtProduct.Select(OrderConstants.Entities.Product.FieldName.ProductID + " = '" + cmbProduct.Text + "'");
                if (row.Length>0)
                {
                    txtUnit.Text = row[0][OrderConstants.Entities.Product.FieldName.UnitID].ToString();
                    txtPrice.Text = (decimal.Parse(row[0][OrderConstants.Entities.Product.FieldName.Price].ToString()).ToString("n2"));
                    price = decimal.Parse(row[0][OrderConstants.Entities.Product.FieldName.Price].ToString());
                    txtCurrencyPrice.Text = row[0][OrderConstants.Entities.Product.FieldName.CurrencyID].ToString();
                    txtProductName.Text = row[0][OrderConstants.Entities.Product.FieldName.ProductName].ToString();
                    txtEnglishName.Text = row[0][OrderConstants.Entities.Product.FieldName.EnglishName].ToString();
                    txtxVietName.Text = row[0][OrderConstants.Entities.Product.FieldName.VietName].ToString();
                    txtJapanName.Text = row[0][OrderConstants.Entities.Product.FieldName.JapanName].ToString();
                    txtSize.Text = row[0][OrderConstants.Entities.Product.FieldName.Size].ToString();
                    txtMakername.Text = row[0][OrderConstants.Entities.Product.FieldName.MakerName].ToString();
                    txtProducrGroup.Text = row[0][OrderConstants.Entities.Product.FieldName.GroupName].ToString();
                    txtSupplierName.Text = row[0][OrderConstants.Entities.Product.FieldName.SupplierName].ToString();
                    txtPurpose.Text = row[0][OrderConstants.Entities.Product.FieldName.PurposeName].ToString();
                    txtKind.Text = row[0][OrderConstants.Entities.Product.FieldName.KindID].ToString();
                }
            }
        }

        void txtExchangeRate_LostFocus(object sender, EventArgs e)
        {
            lbAmount.Visible = true;
            txtAmount.Visible = true;
            txtCurrencyAmount.Visible = true;

            try
            {
                txtAmount.Text =
                ((int.Parse(txtQuantity.Text) * decimal.Parse(txtPrice.Text)) / decimal.Parse(txtExchangeRate.Text)).ToString("n2");
                txtCurrencyAmount.Text = "USD";
            }
            catch (Exception)
            {

                //MessageBox.Show("System cannot calculate amount.");
            }
            
        }

        private void cmbPurchaser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!Utilities.IsNullOrEmpty(cmbPurchaser.SelectedValue) || cmbPurchaser.SelectedItem != cmbPurchaser.Items[0])
            {
                DataRow[] row = dtPurchase.Select(OrderConstants.Entities.Purchaser.FieldName.PurchaseID + " = '" + cmbPurchaser.SelectedValue.ToString() + "'");
                if (row.Length > 0)
                {
                    txtPuchaserName.Text = row[0][OrderConstants.Entities.Purchaser.FieldName.PurchaseName].ToString();
                }
            }
        }

        private void cmbPGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!Utilities.IsNullOrEmpty(cmbPGroup.SelectedValue) || cmbPGroup.SelectedItem != cmbPGroup.Items[0])
            {
                DataRow[] row = dtPGroup.Select(OrderConstants.Entities.PGroup.FieldName.PGroupID + " = '" + cmbPGroup.SelectedValue.ToString() + "'");
                if (row.Length > 0)
                {
                    txtPGroupName.Text = row[0][OrderConstants.Entities.PGroup.FieldName.PGroupName].ToString();
                }
            }
        }

        private void frm_OrderInputAdd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    this.btAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                cmbOrderID.Focus();
            }
        }

        private void cmbProduct_DropDown(object sender, EventArgs e)
        {
            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;

            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cmbProduct":
                        foreach (var item in itemProductID)
                        {
                            cmbProduct.Items.Add(item.ToString());

                        }
                        break;

                }

                int width = combo.DropDownWidth;
                Graphics g = combo.CreateGraphics();
                Font font = combo.Font;
                int vertScrollBarWidth =
                    (combo.Items.Count > combo.MaxDropDownItems)
                    ? SystemInformation.VerticalScrollBarWidth : 0;

                int newWidth;
                foreach (object ite in ((System.Windows.Forms.ComboBox)sender).Items)
                {
                    newWidth = (int)g.MeasureString(ite.ToString(), font).Width
                        + vertScrollBarWidth;
                    if (width < newWidth)
                    {
                        width = newWidth;
                    }
                }
                combo.DropDownWidth = width;
                Cursor.Current = Cursors.Default;


            }
        }

        private void cmbProductName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

    }
}